package client;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.util.ArrayList;

import entry.Entry;
import event.Event;
import event.EventHandler;

public class ServerDirectoryEventHandler implements EventHandler {

	@Override
	public void handle(Event e) {

	}

	public static void sendDirectoryList(File dir, DataOutputStream os)
			throws IOException {
		InetAddress ip = InetAddress.getLocalHost();
		if (ip.isLoopbackAddress()) {
			System.out.println("Only have local loopback");
			return;
		}

		ArrayList<Entry> files = getFileNames(new ArrayList<Entry>(), dir);

		/*
		 * Send the header.
		 */
		os.writeInt(Event.DIR_TYPE);
		os.writeLong(0);
		os.writeLong(0);

		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		ObjectOutputStream aos = new ObjectOutputStream(bos);
		aos.writeObject(files);

		os.writeInt(bos.size());
		os.writeUTF(ip.getHostAddress());

		bos.writeTo(os);

		bos.close();
		aos.close();
	}

	private static ArrayList<Entry> getFileNames(ArrayList<Entry> list,
			File file) {
		if (file != null) {
			File[] files = file.listFiles(CustomFileFilter.getInstance());
			for (File f : files) {
				if (f.isFile()) {
					String value = f.getAbsolutePath();
					int index = value.lastIndexOf(File.separator);
					int len = value.length();

					String key;
					if (index >= 0) {
						if (index >= len - 1) {
							// We don't want to accept files with the file
							// separator as their last character. This will
							// never happen anyways, but just a precaution...
							continue;
						}
						key = value.substring(index + 1);
					} else {
						key = value;
					}

					list.add(new Entry(key, value));
				} else {
					getFileNames(list, f);
				}
			}
		}
		return list;
	}
}
